<?php

class Application_Model_wayBillItem extends Application_Model_DomainObject implements Application_Model_PayInterface {

// `discountFee`, `serviceFee`, `shipFee`, `status`, `useScore`, `userId`, `noSkin`, `shipType`, `shipFeeconfig`, `shipMoney`, `consignee`, `conAdd`, `conTel`, `conPostCode`, `bagWeight`, `weight`, `logistics`, `comment`
    protected $_id; //序号
    protected $_billNo; //UUCH内部运单号
    protected $_dateCreated; //创建日期
    protected $_dateSend; //发货日期
    protected $_dateUserConfrim; //用户确认收货日期
    protected $_datePaid; //付款日期
    protected $_lastdate; //最后更新时间------
    protected $_status; //前台状态 0:等待付款 1：受理中(正在发货) 2:已经发货 100：已经完成 -1:取消 -2:海关退货；
    protected $_userId; //用户ID
    protected $_weight; //结算重量
    protected $_bagWeight; //包裹重量
    protected $_volumeWeight; //体积重量--------
    protected $_productWeight; //物品总重量-------
    protected $_lastWeight; //最终重量-----------
    protected $_isVolume; //是否收了体积重量XXX
    protected $_expressId; //运送方式
    protected $_shipType; //运送方式 从Express里面取值
    protected $_shipFeeconfig; //运送方式  从ExpressPrice里面取值
    protected $_state; //国家--------
    protected $_consignee; //收货人
    protected $_conAdd; //收货人地址
    protected $_conTel; //收货人电话
    protected $_conPostCode; //收货人邮编            
    protected $_isNoLogo; //是否去掉吊牌，Logo等------
    protected $_isNoSkin; //是否要去掉不必要包装---------
    protected $_isCompress; //是否要压缩抽气----------
    protected $_discountFee; //折扣金额
    protected $_serviceFee; //服务费
    protected $_shipFee; //邮费
    protected $_shipMoney; //预收总运费   
    protected $_reportFee; //报关费---------
    protected $_lastMoney; //最终收款----------
    protected $_costMoney; //成本价----------    
    protected $_useScore; //使用积分
    protected $_logistics; //物流单号
    protected $_agentId; //货代公司
    protected $_agentNo; //代理公司单号
    protected $_comment; //评论序号
    protected $_refundMoney;  //订单退款
    protected $_lastVolumeWeight; //最终体积重量
    protected $_expressCostId; //快递成本ID，用于标记快递走了哪一个通道，用了多少成本
    protected $_channer; //渠道
    protected $_remark; //备注
    protected $_lwhth; //长宽高
    protected $_fee; //住宅费
    protected $_interior; //内部状态
    protected $_problem; //问题状态
    protected $_isWooden; //木架加固
    protected $_paymentWeight;//预付重量
    protected $_isInvoice;//是否已出发票
    protected $_isAddform;//是否已打印地址标签
    protected $_dutyNo;//税号
    /**
     *  等待付款
     */

    const STATUS_WaitPay = 0;
    /**
     * 等待受理
     */
    const STATUS_Processing = 1;
    /**
     * 已经发货
     */
    const STATUS_Sended = 2;
    /**
     * 已受理
     */
    const STATUS_Confrimed = 3;
    /**
     * 已经完成
     */
    const STATUS_Complated = 100;
    /**
     * 取消
     */
    const STATUS_Cancel = -1;

    /**
     * 海关退货
     */
    const STATUS_Back = -2;

    /**
     * 快递拒收 
     */
    const STATUS_NoAppect = -3;

    /**
     * 快递退包 
     */
    const STATUS_ExpressBack = -4;
    /**
     * 未付款
     */
    const Interior_WaitPay = 0;
    /**
     * 待受理
     */
    const Interior_Processing = 1;
    /**
     * 已受理待选择渠道
     */
    const Interior_Confrimed = 2;
    /**
     * 已选择渠道待拣货
     */
    const Interior_Incoice = 3;
    /**
     * 已拣货待打包
     */
    const Interior_Picking = 4;
    /**
     * 拣货异常
     */
    const Interior_PickError = 20;
    /**
     * 已打包待确认渠道
     */
    const Interior_Pick = 5;
    /**
     * 已确认渠道待交运
     */
    const Interior_AffirmChannel = 6;
    /**
     * 已交运待上系统
     */
    const Interior_Outstorage = 10;
    /**
     * 已上系统
     */
    const Interior_System = 11;
    /**
     * 上系统超期
     */
    const Interior_OverSystem = 21;
    /**
     * 已出转单
     */
    const Interior_Singleno = 12;
    /**
     * 出转单超期
     */
    const Interior_Oversingleno = 22;
    /**
     * 已上网
     */
    const Interior_Transportation = 13;
    /**
     * 上网超期
     */
    const Interior_OutTransportation = 23;
    /**
     * 完成超期
     */
    const Interior_Overachieve = 24;
    /**
     * 已完成
     */
    const Interior_Achieve = 100;
    
    /**
     * 已取消
     */
    const Interior_Cancel = -1;

    /**
     * 状态枚举
     * @return array 
     */
    public static function getStatusEnum() {
        return array(0 => '等待付款', 1 => '等待受理', 2 => '已经发货', 3 => '已经受理', 100 => '已经完成', -1 => '取消', -2 => '海关退货', -3 => '快递拒收', -4 => '快递退包');
    }

    /**
     * 设置运单重量
     * @param type $weight 结算重量
     * @param type $bagWeight 包裹重量
     * @param type $productWeight 物品总重量
     * @param type $volumWeight 物品体积重量
     */
    public function setAllWeight($weight, $bagWeight, $productWeight, $volumeWeight) {
        $this->_weight = $weight;
        $this->_bagWeight = $bagWeight;
        $this->_productWeight = $productWeight;
        $this->_volumeWeight = $volumeWeight;
    }

    /**
     * 设置收货地址
     * @param Application_Model_address $address 
     */
    public function setAddress($address) {
        $this->_state = $address->State;
        $this->_consignee = $address->LinkMan; //收货人
        $this->_conAdd = $address->Street; //收货人地址
        $this->_conTel = $address->Mobile; //收货人电话
        $this->_conPostCode = $address->Postcode; //收货人邮编            
    }

    /**
     * 设置运单金额
     * @param type $shipMoney 预收总运费
     * @param type $shipFee 邮费
     * @param type $reportFee 报关货
     * @param type $discountFee 折扣金额
     * @param type $serviceFee 服务费
     */
    public function setAllMoney($shipMoney, $shipFee, $reportFee, $discountFee, $serviceFee) {
        $this->_shipMoney = $shipMoney;
        $this->_shipFee = $shipFee;
        $this->_reportFee = $reportFee;
        $this->_serviceFee = $serviceFee;
        $this->_discountFee = $discountFee;
    }

    private $_logisticsItems; //运单物流信息

    /*
     * 获取当前运单物流信息
     */

    public function logisticsItems() {
        if (!empty($this->_logisticsItems)) {
            return $this->_logisticsItems;
        } else {

            if ($this->_logistics) {
                $this->_logisticsItems = Application_Model_logisticslogItem::getByNo($this->_logistics);
                return $this->_logisticsItems;
            } else {
                return null;
            }
        }
    }

    public function getLogisticsItems() {
        if (!$this->_logisticsItems) {
            $this->_logisticsItems = Application_Model_logisticslogItem::getByWayId($this->_id);
        }
        return $this->_logisticsItems;
    }

    private $_storeItems;

    /*
     * 仓库信息
     */

    public function getStoreItems() {
        if (empty($this->_storeItems)) {
            if (count($this->getItems()) == 0) {
                $this->_storeItems = Application_Model_StoreItem::getBywayId($this->Id);
            } else {
                $this->_storeItems = Uuch_Util::select($this->getItems(), function($item) {
                                    return Application_Model_StoreItem::load($item->StoreItemId);
                                });
            }
        }
        return $this->_storeItems;
    }

    private $_agent;

    public function getAgentBy() {
        if ($this->_agent == NULL)
            $this->_agent = Application_Model_AgentCompany::load($this->_agentId);
        return $this->_agent;
    }

    /**
     * 返回运单当前状态
     * @return type 
     */
    public function getStatusName() {
        $names = Application_Model_wayBillItem::getStatusEnum();
        return $names[$this->_status];
    }
    

    public function statusname() {

        switch ($this->_status) {
            case 0:
                return "等待付款";
                break;
            case 1:
                return "正在发货";
                break;
            case 2:
                return "已经发货";
                break;
            case 100:
                return "已经完成";
                break;
            case -1:
                return "已经撤消";
                break;
            case -2:
                return "海关退货";
                break;
        }

        //状态 0:等待付款 1：受理中(正在发货) 2:已经发货 100：已经完成 -1:取消 -2:海关退货；
    }

    /*
     * 获取用户名
     */

    public function username() {
        $user = Application_Model_User::load($this->_userId);

        return $user->nikename;
    }

    /*
     * 返回数据持久化对象
     * @return Application_Model_StoreItem
     */

    protected static function getDb() {
        return new Application_Model_DbTable_wayBillItem();
    }

    /*
     * 根据userid返回一个数组
     * @param int $userid
     * @return array
     */

    public static function getByuserId($userid, $state, $start, $row) {

        $result = Application_Model_wayBillItem::getDb()->getByUser($userid, $state, $start, $row); //

        /* foreach ($result as $item){
          if($item->id!=null)
          {
          $item->product = new Application_Model_Product($item->id);
          }
          } */

        return $result;
    }

    /*
     * 根据用户名，状态获取当前记录总数
     * @param int $userid 用户序号
     * @param int $state 用户序号
     * @return int
     */

    public static function getItemCount($userid, $state) {

        $bill = new Application_Model_DbTable_wayBillItem();

        return $bill->getItemCount($userid, $state);
    }

    /**
     * 确认收货
     */
    public static function sign($id) {
        if ($id > 0) {
            $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
            $db = $bootstrap->getResource('db');
            $set = array(
                'status' => 100,
                'dateUserConfrim' => date('Y-m-d H:i:s'),
            );
            $where = $db->quoteInto('id = ?', $id);
            $rows_affected = $db->update('uuch_waybill', $set, $where);

            if ($rows_affected > 0) {
//                $getItem = new Application_Model_wayBillItem($id);
//                    //更新物流信息
//                    $newitem=new Application_Model_logisticslogItem();
//                    $newitem->logisticsNo=$getItem->logistics;//物流单号
//                    $newitem->opDate=date('Y-m-d H:i:s');//操作时间
//                    $newitem->opRemark=$getItem->conAdd;//操作描述
//                    $newitem->opState="用户确认收货";//操作状态
//                    $newitem->opUser=$getItem->userId;;//操作者
//                    $newitem->save();
                return true;
            }

            return false;
        }

        return false;
    }

    /**
     * 根据指定的条件返回运单
     * @param int $wayid
     * @param int $memberId
     * @param date $startTime 开始时间
     * @param date $endTime 结束时间
     * @param int $status 订单状态
     * @param int $count
     * @param int $offset
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($wayid, $memberId, $startTime, $endTime, $status, $count, $offset) {
        $where = array();
        $and = '';
        if ($wayid != NULL) {
            $where['Id = '] = $wayid;
            $and = ' and ';
        }

        if ($memberId != NULL) {
            $where[$and . ' userId = '] = $memberId;
            $and = ' and ';
        }

        if ($startTime != NULL) {
            $where[$and . ' dateCreated >= '] = $startTime;
            $and = ' and ';
        }

        if ($endTime != NULL) {
            $where[$and . ' dateCreated <= '] = $endTime;
            $and = ' and ';
        }

        if ($status != NULL) {
            $where[$and . ' status = '] = $status;
            $and = ' and ';
        }

        return Application_Model_wayBillItem::getDb()->queryPage($where, 'dateCreated desc', $count, $offset);
    }

    public function getMoney() {
        return $this->ShipMoney;
    }

    public function getPayName() {
        return '国际运单';
    }

    public function setPaid() {
        $this->_status = Application_Model_wayBillItem::STATUS_Processing;
        $this->_interior = self::Interior_Processing;
        $this->_datePaid = date('Y-m-d H:i:s');
    }

    public function canPay($userId) {
        if ($this->_userId != $userId)
            return FALSE;

        if ($this->_status != Application_Model_wayBillItem::STATUS_WaitPay)
            return FALSE;

        return TRUE;
    }

    public function getShipName() {
        return $this->getShipTypeBy()->Name;
    }

    private $shipBy;

    /**
     * 返回对应的快递公司 ,ShipType表与Express表ID一样，如要取物流信息，需要从ShipType取数据
     */
    public function getShipTypeBy() {
        if (!isset($this->shipBy)) {
            $this->shipBy = Application_Model_shipType::load($this->_shipType);
        }
        return $this->shipBy;
    }

    private $express;

    public function getExpressBy() {
        if ($this->express == NULL)
            $this->express = Application_Model_Express::load($this->_expressId ? $this->_expressId : $this->_shipType);
        return $this->express;
    }

    public function getBillNo() {
        return $this->_billNo;
    }

    public function getPayDescription() {
        return '支付悠奇国际运单费用，用户名:' . Application_Model_User::load($this->_userId)->Email;
    }

    private $_cityBy = null;

    public function getCityBy() {
        if ($this->_cityBy == NULL)
            $this->_cityBy = Application_Model_city::load($this->_state);
        return $this->_cityBy;
    }

    /**
     * 取消运单 
     */
    public function cancelWay() {
        try {
            $this->getDbTable()->beginTran();

            foreach ($this->getStoreItems() as $item) {
                $item->WayId = NULL;
                $item->State = Application_Model_StoreItem::STATUS_InStored;
                $item->save();
            }

            $coupons = Application_Model_Coupon::getByWayId($this->id);
            foreach ($coupons as $coupon) {
                $coupon->Relevance = null;
                $coupon->Status = Application_Model_Coupon::STATUS_OK;
                $coupon->save();
            }

            if ($this->_status == Application_Model_wayBillItem::STATUS_Processing) {
                $account = Application_Model_UserAccount::load($this->_userId);

                $history = new Application_Model_UserAccountHistory();
                $history->Type = Application_Model_UserAccountHistory::TYPE_RECHARGE_MONEY;
                $history->BeforeMoney = $account->Money;
                $history->AfterMoney = $account->Money + $this->_shipMoney;
                $history->Comment = '取消运单退款';
                $history->DateCreated = date('Y-m-d H:i:s');
                $history->RelaseId = $paybill->Id;
                $history->BeforeScore = $account->Score;

                $history->AfterScore = $account->Score;
                $history->AccountId = $account->Id;
                $history->save();

                $account->Money += $this->_shipMoney;
                $account->save();
            }
            $this->_status = Application_Model_wayBillItem::STATUS_Cancel;
            $this->_interior = self::Interior_Cancel;
            $this->save();
            $this->getDbTable()->commit();
        } catch (Exception $ex) {
            $this->getDbTable()->rollBack();
            throw $ex;
        }
    }

    private $_items;

    /**
     * 返回运单中所有的货物
     */
    public function getItems() {
        if ($this->_items == NULL) {
            $this->_items = Application_Model_WayItem::getByWayId($this->_id);
        }
        return $this->_items;
    }

    /**
     * 往运单里面添加货物
     * @param type $storeItem
     */
    public function addItem($storeItemId) {
        $items = $this->getItems();
        $newItem = new Application_Model_WayItem();
        $newItem->WayId = $this->_id;
        $newItem->StoreItemId = $storeItemId;
        $newItem->Status = 0;
        $newItem->save();
        $items[] = $newItem;
    }

    private $_fees;

    /**
     * 返回运单的费用明细
     */
    public function getFees() {
        if ($this->_fees == NULL) {
            $this->_fees = Application_Model_WayFee::getByWayId($this->_id);
        }
        return $this->_fees;
    }

    /**
     * 跟据类型返回服务费用
     * @param int $feeType
     * @return int
     */
    public function getFeeByType($feeType) {
        $fee = Uuch_Util::first($this->getFees(), function($item) use($feeType) {
                            return $item->FeeType == $feeType;
                        });
        if ($fee) {
            return $fee->Money;
        } else {
            switch ($feeType) {
                case Application_Model_FeeType::CouponFee:
                    return $this->_discountFee;
                case Application_Model_FeeType::EstimateShipFee:
                    return $this->_shipFee;
                case Application_Model_FeeType::EstimateSum:
                    return $this->_shipMoney;
                case Application_Model_FeeType::LastSum:
                    return $this->_lastMoney;
                case Application_Model_FeeType::StoreServiceFee:
                    return $this->_serviceFee;
                case Application_Model_FeeType::ReportFee:
                    return $this->_reportFee;
                case Application_Model_FeeType::CostFee:
                    return $this->_costMoney;
                case Application_Model_FeeType::RefoundFee:
                    return $this->_refundMoney;
            }
            return 0;
        }
    }

    /**
     * 添加一个费用
     */
    public function addFee($feeType, $money) {
        $fees = $this->getFees();
        $fee = new Application_Model_WayFee();
        $fee->FeeType = $feeType;
        $fee->Money = $money;
        $fee->WayId = $this->_id;
        $fee->save();
        $fees [] = $fee;
    }

    private $_logs;

    /**
     * 返回运单的操作详情
     */
    public function getLogs() {
        if ($this->_logs == NULL) {
            $this->_logs = Application_Model_WayLog::getByWayId($this->_id);
        }
        return $this->_logs;
    }

    /**
     * 添加运单操作日期
     * @param type $desc 操作说明
     * @param type $isShow 是否在前台显示
     * @param type $operator 操作人
     */
    public function addLog($desc, $isShowFront, $operator) {
        $log = new Application_Model_WayLog();
        $log->DateCreated = date('Y-m-d H:i:s');
        $log->Description = $desc;
        $log->IsShowFront = $isShow;
        $log->Operator = $operator;
        $log->WayId = $this->_id;
        $log->save();
    }
    public function getBillIdDelLog()
    {
        $logItem = Application_Model_WayLog::getDao()->queryAll(array("wayId"=>  $this->_id,"and operateType<200 and operateType > "=>  $this->_interior));
        if($logItem){
            foreach ($logItem as $logVal) {
                $logVal->delete();
            }
        }
    }
    private $_weights;

    /**
     * 返回运单的所有重量信息
     * @return type
     */
    public function getWeights() {
        if ($this->_weights == NULL) {
            $this->_weights = Application_Model_WayWeight::getByWayId($this->_id);
        }
        return $this->_weights;
    }

    /**
     * 添加一个重量信息
     * @param type $type
     * @param type $weight
     */
    public function addWeight($type, $weight) {
        $weightItem = new Application_Model_WayWeight();
        $weightItem->Type = $type;
        $weightItem->Weight = $weight;
        $weightItem->WayId = $this->_id;
        $weightItem->save();
        $weights = $this->getWeights();
        $weights[] = $weightItem;
    }

    /**
     * 修改一个重量信息
     * @param type $type
     * @param type $weight
     */
    public function editWeight($type, $weight) {
        $weightItem = Application_Model_WayWeight::getWeightByType($this->_id, $type);
        if ($weightItem == null) {
            $this->addWeight($type, $weight);
            return;
        }
        $weightItem->weight = $weight;
        $weightItem->save();
    }

    /**
     * 运单的最终结算重量
     */
    public function getClosingWeight() {
        $weight = $this->_isVolume && $this->_lastVolumeWeight ? $this->_lastVolumeWeight : $this->_lastWeight;
        return $weight;
    }

    /**
     * 当前重量,如果已经有了结算重量，则显示最终重量，如果没有，就显示预估重量
     */
    public function getCurrentWeight() {
        if ($this->getClosingWeight())
            return $this->getClosingWeight();
        return $this->_isVolume && $this->_volumeWeight ? $this->_volumeWeight : $this->_weight;
    }

    /**
     * 返回运单的所有发货渠道可选项 
     */
    public function getCostOption() {
        return Application_Model_ExpressCost::getByExpressAndCity($this->_shipType, $this->_state, $this->getCurrentWeight());
    }

    /**
     * 获取今日运单详情
     * @param type $state 运单详情
     */
    public static function getcountbill($interior, $problem, $day = null) {
        $where = array();
        $and = '';
        if (!is_null($interior)) {
            $where[" interior = "] = $interior;
            $and = " and ";
        }
        if ($problem != "") {
            $where[$and . " problem = "] = $problem;
            $and = " and ";
        }  else {
            $where[$and . " ( problem = 0 or problem is null ) and "] = 1;
            $and = " and ";
        }
        if ($day == 1) {
            $where[$and . " dateCreated > "] = date("Y-m-d");
            $and = " and ";
        }
//        var_dump($where);exit;
        return Application_Model_wayBillItem::getDao()->count($where);
    }

    public static function getBillcount($dateinbegin, $dateinend) {
        $where = "";
        $and = "";
        $where[" status > "] = Application_Model_wayBillItem::STATUS_Processing;
        $and = " and ";
        if ($dateinbegin != "" && $dateinend == "") {
            $where[$and . " dateCreated > "] = $dateinbegin . " 00:00:00";
            $and = " and ";
            $where[$and . " dateCreated < "] = $dateinbegin . " 23:59:59";
            $result = Application_Model_wayBillItem::getDb()->queryAll($where);
            $i = strtotime($dateinbegin);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["zyfk"] = 0;
            $arrre[$i]["zsfk"] = 0;
            $arrre[$i]["zcbj"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["zyfk"] = $arrre[$i]["zyfk"] + $value->shipMoney;
                    $arrre[$i]["zsfk"] = $arrre[$i]["zsfk"] + $value->lastMoney;
                    $arrre[$i]["zcbj"] = $arrre[$i]["zcbj"] + $value->costMoney;
                }
            }
            $where[$and . " agentId = "] = 3;
            $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["hlynum"] = count($hlyresult);
            $arrre[$i]["hlyzyfk"] = 0;
            if ($hlyresult) {
                foreach ($hlyresult as $value) {
                    $arrre[$i]["hlyzyfk"] = $arrre[$i]["hlyzyfk"] + $value->shipMoney;
                }
            }
            $where[$and . " agentId = "] = 2;
            $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["sdnum"] = count($sdresult);
            $arrre[$i]["sdzyfk"] = 0;
            if ($sdresult) {
                foreach ($sdresult as $value) {
                    $arrre[$i]["sdzyfk"] = $arrre[$i]["sdzyfk"] + $value->shipMoney;
                }
            }
        }
        if ($dateinend != "" && $dateinbegin == "") {
            $where[$and . " dateCreated > "] = $dateinend . " 00:00:00";
            $and = " and ";
            $where[$and . " dateCreated < "] = $dateinend . " 23:59:59";
            $result = Application_Model_wayBillItem::getDb()->queryAll($where);
            $i = strtotime($dateinend);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["zyfk"] = 0;
            $arrre[$i]["zsfk"] = 0;
            $arrre[$i]["zcbj"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["zyfk"] = $arrre[$i]["zyfk"] + $value->shipMoney;
                    $arrre[$i]["zsfk"] = $arrre[$i]["zsfk"] + $value->lastMoney;
                    $arrre[$i]["zcbj"] = $arrre[$i]["zcbj"] + $value->costMoney;
                }
            }
            $where[$and . " agentId = "] = 3;
            $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["hlynum"] = count($hlyresult);
            $arrre[$i]["hlyzyfk"] = 0;
            if ($hlyresult) {
                foreach ($hlyresult as $value) {
                    $arrre[$i]["hlyzyfk"] = $arrre[$i]["hlyzyfk"] + $value->shipMoney;
                }
            }
            $where[$and . " agentId = "] = 2;
            $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
            $arrre[$i]["sdnum"] = count($sdresult);
            $arrre[$i]["sdzyfk"] = 0;
            if ($sdresult) {
                foreach ($sdresult as $value) {
                    $arrre[$i]["sdzyfk"] = $arrre[$i]["sdzyfk"] + $value->shipMoney;
                }
            }
        }
        if ($dateinend != "" && $dateinbegin != "") {
            $sdate = $dateinbegin <= $dateinend ? $dateinbegin : $dateinend;
            $edate = $dateinbegin >= $dateinend ? $dateinbegin : $dateinend;
            $stime = strtotime($sdate);
            $etime = strtotime($edate);
            for ($i = $stime; $i <= $etime; $i++) {
                $where = "";
                $and = "";
                $where[" status > "] = Application_Model_wayBillItem::STATUS_Processing;
                $and = " and ";
                $where[$and . " dateCreated > "] = date("Y-m-d H:i:s", $i);
                $where[$and . " dateCreated < "] = date("Y-m-d H:i:s", ($i + 86400));
                $result = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$i]["num"] = count($result);
                $arrre[$i]["zyfk"] = 0;
                $arrre[$i]["zsfk"] = 0;
                $arrre[$i]["zcbj"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$i]["zyfk"] = $arrre[$i]["zyfk"] + $value->shipMoney;
                        $arrre[$i]["zsfk"] = $arrre[$i]["zsfk"] + $value->lastMoney;
                        $arrre[$i]["zcbj"] = $arrre[$i]["zcbj"] + $value->costMoney;
                    }
                }
                $where[$and . " agentId = "] = 3;
                $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$i]["hlynum"] = count($hlyresult);
                $arrre[$i]["hlyzyfk"] = 0;
                if ($hlyresult) {
                    foreach ($hlyresult as $value) {
                        $arrre[$i]["hlyzyfk"] = $arrre[$i]["hlyzyfk"] + $value->shipMoney;
                    }
                }
                $where[$and . " agentId = "] = 2;
                $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$i]["sdnum"] = count($sdresult);
                $arrre[$i]["sdzyfk"] = 0;
                if ($sdresult) {
                    foreach ($sdresult as $value) {
                        $arrre[$i]["sdzyfk"] = $arrre[$i]["sdzyfk"] + $value->shipMoney;
                    }
                }
                $i+= 86399;
            }
        }
        if ($dateinend == "" && $dateinbegin == "") {
            $arrre = array();
            $nowYm = date("Y-m");
            $nowd = date("d");
            for ($i = 1; $i <= $nowd; $i++) {
                $where = "";
                $and = "";
                $where[" status > "] = Application_Model_wayBillItem::STATUS_Processing;
                $and = " and ";
                $where[$and . " dateCreated > "] = $nowYm . "-" . $i;
                $where[$and . " dateCreated < "] = $nowYm . "-" . ($i + 1);
                $result = Application_Model_wayBillItem::getDb()->queryAll($where);
                $j = strtotime($nowYm . "-" . $i);
                $arrre[$j]["num"] = count($result);
                $arrre[$j]["zyfk"] = 0;
                $arrre[$j]["zsfk"] = 0;
                $arrre[$j]["zcbj"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$j]["zyfk"] = $arrre[$j]["zyfk"] + $value->shipMoney;
                        $arrre[$j]["zsfk"] = $arrre[$j]["zsfk"] + $value->lastMoney;
                        $arrre[$j]["zcbj"] = $arrre[$j]["zcbj"] + $value->costMoney;
                    }
                }
                $where[$and . " agentId = "] = 3;
                $hlyresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$j]["hlynum"] = count($hlyresult);
                $arrre[$j]["hlyzyfk"] = 0;
                if ($hlyresult) {
                    foreach ($hlyresult as $value) {
                        $arrre[$j]["hlyzyfk"] = $arrre[$j]["hlyzyfk"] + $value->shipMoney;
                    }
                }
                $where[$and . " agentId = "] = 2;
                $sdresult = Application_Model_wayBillItem::getDb()->queryAll($where);
                $arrre[$j]["sdnum"] = count($sdresult);
                $arrre[$j]["sdzyfk"] = 0;
                if ($sdresult) {
                    foreach ($sdresult as $value) {
                        $arrre[$j]["sdzyfk"] = $arrre[$j]["sdzyfk"] + $value->shipMoney;
                    }
                }
            }
        }

//        var_dump($arrre);exit;
        return $arrre;
    }

    public static function getBillAll($balusc, $agentid, $expressId, $dateselect, $starttime, $endtime, $status, $problem, $pagesize, $pageindex, $userid = null, $invoice = null,$day = null,$cityid = null,$startweight = null,$endweight = null,$startpayment = null,$endpayment = null,$startmoney = null,$endmoney = null) {
        $where = array();
        $and = '';
        $or = '';
        $order = 'dateCreated desc';
        if ($balusc != '') {
            $balusc = trim($balusc);
            $num = strlen($balusc);
            $or = "( ";
            if($num == 5){
                $uwhere[ ' storeno = '] = $balusc;
                $user = Application_Model_User::getDao()->queryOne($uwhere);
                if ($user) {
                    $where[$or . ' userId = '] = $user->id;
                    $or = " or ";
                }
            }else if($num == 11){
                $storeItem = Application_Model_StoreItem::bybarcode($balusc);
                $wayid = "(";
                if($storeItem){
                    foreach ($storeItem as $storevalue) {
                        $wayItem = $storevalue->getStoreIdWay();
                        if($wayItem){
                            foreach ($wayItem as $wayval) {
                                $wayid .= $wayval->wayId.",";
                            }
                        }
                    }
                }
                $wayid .= "0)";
                $where[$or . " id in "] = $wayid;
                $or = " or ";
            }  else {
                $where[$or . ' billNo = '] = $balusc;
                $or = " or ";
                $where[$or . ' agentNo = '] = $balusc;
                $where[$or . ' logistics = '] = $balusc;
            }        
            $where[") and "] = "1=1";
            $and = ' and ';
        }
       
        if ($starttime != '') {
            $where[$and  . 'datePaid >='] = $starttime . " 00:00:00";
            $and = ' and ';
        }
        if ($endtime != '') {
            $where[$and  . 'datePaid <='] = $endtime . " 23:59:59";
            $and = ' and ';
        }

        if ($agentid != '') {
            $where[$and . ' agentId = '] = $agentid;
            $and = ' and ';
        }
        if ($expressId != '') {
            $where[$and . ' expressId = '] = $expressId;
            $and = ' and ';
        }
        if (!is_null($status) && $status != "") {
            $where[$and . " interior = "] = $status;
            $and = " and ";
            if ($status == Application_Model_wayBillItem::Interior_Processing) {
                $order = 'dateCreated asc';
            }
        }
        if ($problem != null) {
            $where[$and . " problem = "] = $problem;
            $and = " and ";
        } else {
            $where[$and . " ( problem = 0 or problem is null ) and "] = 1;
            $and = " and ";
        }
        if ($userid != null) {
            $where[$and . ' userId = '] = $userid;
            $and = ' and ';
        }
        if ($invoice != 0) {
            $where[$and . ' isInvoice = '] = 0;
            $and = ' and ';
            $where[$and . " interior > "] = Application_Model_wayBillItem::Interior_Processing;
        }
        if ($day != null){
            $where[$and . ' dateCreated > '] = date("Y-m-d");
            $and = ' and ';
        }
        if($cityid != null){
            $where[$and." state = "] = $cityid;
            $and  = " and ";
        }
        if($startweight != null && $endweight != null)
        {
            $where[$and." productWeight >= "] = $startweight*1000;
            $where[$and." productWeight <= "] = $endweight*1000;
        }
        if($startpayment != null && $endpayment != null)
        {
            $where[$and." paymentWeight >= "] = $startpayment*1000;
            $where[$and." paymentWeight <= "] = $endpayment*1000;
        }
        if($startmoney != null && $endmoney != null)
        {
            
            $where[$and." shipMoney >= "] = $startmoney;
            $where[$and." shipMoney <= "] = $endmoney;
        }
//        var_dump($where);
        return Application_Model_wayBillItem::getDao()->queryPage($where, $order, $pagesize, $pageindex);
    }
    
    public function getstatustype() {
        if ($this->_status == Application_Model_wayBillItem::STATUS_Complated || $this->_status == Application_Model_wayBillItem::STATUS_Cancel) {
            return false;
        } else {
            return true;
        }
    }
    public function getstatusUnify()
    {
        if($this->_interior == Application_Model_wayBillItem::Interior_AffirmChannel){
            return true;
        }  else {
            return false;
        }
    }

    public function getuser() {
        return new Application_Model_User($this->_userId);
    }

    public function getUserCity() {
        $id = $this->_state;
        return Application_Model_city::load($id);
    }

    public function getagentname() {
        return Application_Model_AgentCompany::load($this->_agentId);
    }

    /**
     * 获取运送方式的全部下级方式
     */
    public function getExpresschannel() {
        $where[' 1 = '] = 1;
        return Application_Model_ExpressChannel::getDao()->queryAll($where, "expressId asc");
    }

    public function getExpressbychannelOne() {
        if($this->_expressId){
            $where['expressId = '] = $this->_expressId;
            return Application_Model_Expressbychannel::getDao()->queryAll($where, "expressId asc");
        }
    }

    public function getExpresschannelOne() {
        if($this->getExpressbychannelOne()){
        return Uuch_Util::select($this->getExpressbychannelOne(), function($item) {
                            return Application_Model_ExpressChannel::load($item->expressChannelId);
                        });
        }
    }
    public static function getInteriorAll()
    {
        return array(
                Application_Model_wayBillItem::Interior_WaitPay=>"待付款"
               ,Application_Model_wayBillItem::Interior_Processing=>"待受理"
               ,Application_Model_wayBillItem::Interior_Confrimed=>"待选择渠道"
               ,Application_Model_wayBillItem::Interior_Incoice=>"待拣货"
               ,Application_Model_wayBillItem::Interior_Picking=>"待打包"
               ,Application_Model_wayBillItem::Interior_Pick=>"待确认渠道"
               ,Application_Model_wayBillItem::Interior_AffirmChannel =>'待交运'
               ,Application_Model_wayBillItem::Interior_Outstorage=>"已交运"
               ,Application_Model_wayBillItem::Interior_System=>"已入系统"
               ,Application_Model_wayBillItem::Interior_Singleno=>"已出转单"
               ,Application_Model_wayBillItem::Interior_Transportation=>"已上网"
               ,Application_Model_wayBillItem::Interior_Achieve=>"已经完成"
               ,Application_Model_wayBillItem::Interior_PickError=>"拣货异常"
               ,Application_Model_wayBillItem::Interior_OverSystem=>"入系统超期"
               ,Application_Model_wayBillItem::Interior_Oversingleno=>"转单超期"
               ,Application_Model_wayBillItem::Interior_OutTransportation=>"上网异常"
               ,Application_Model_wayBillItem::Interior_Overachieve=>"签收预警"
               ,Application_Model_wayBillItem::Interior_Cancel =>"已经取消"
               );
    }
    public static function getEditInteriorAll()
    {
        return array(
                Application_Model_wayBillItem::Interior_WaitPay=>"待付款"
               ,Application_Model_wayBillItem::Interior_Processing=>"待受理"
               ,Application_Model_wayBillItem::Interior_Confrimed=>"待选择渠道"
               ,Application_Model_wayBillItem::Interior_Incoice=>"待拣货"
               ,Application_Model_wayBillItem::Interior_Picking=>"待打包"
               ,Application_Model_wayBillItem::Interior_Pick=>"待确认渠道"
               ,Application_Model_wayBillItem::Interior_AffirmChannel =>'待交运'
               ,Application_Model_wayBillItem::Interior_Outstorage=>"已交运"
               ,Application_Model_wayBillItem::Interior_System=>"已入系统"
               ,Application_Model_wayBillItem::Interior_Singleno=>"已出转单"
               ,Application_Model_wayBillItem::Interior_Transportation=>"已上网"
               ,Application_Model_wayBillItem::Interior_Achieve=>"已经完成"
               );
    }
    public static function getInteriorCorrect()
    {
        return array(
            Application_Model_wayBillItem::Interior_Confrimed => array("待受理", "已受理")
            , Application_Model_wayBillItem::Interior_Incoice => array("待选择渠道", "已选择渠道")
            , Application_Model_wayBillItem::Interior_Picking => array("待拣货", "已拣货")
            , Application_Model_wayBillItem::Interior_Pick => array("待打包", "已打包")
            , Application_Model_wayBillItem::Interior_AffirmChannel => array("待确认渠道", "已确认渠道")
            , Application_Model_wayBillItem::Interior_Outstorage => array('待交运', "已交运")
            , Application_Model_wayBillItem::Interior_System => array("待入系统", "已入系统")
            , Application_Model_wayBillItem::Interior_Singleno => array("待出转单", "已出转单")
            , Application_Model_wayBillItem::Interior_Transportation => array("待上网", "已上网")
            , Application_Model_wayBillItem::Interior_Achieve => array("待签收", "已签收")
        );
    }
    public function getinteriorname() {
        switch ($this->_interior) {
            case Application_Model_wayBillItem::Interior_WaitPay:
                return "未付款";
                break;
            case Application_Model_wayBillItem::Interior_Processing:
                return "待受理";
                break;
            case Application_Model_wayBillItem::Interior_Confrimed:
                return "待选择渠道";
                break;
            case Application_Model_wayBillItem::Interior_Incoice:
                return "待拣货";
                break;
            case Application_Model_wayBillItem::Interior_Picking:
                return "待打包";
                break;
            case Application_Model_wayBillItem::Interior_Pick:
                return "待确认渠道";
                break;
            case Application_Model_wayBillItem::Interior_AffirmChannel:
                return "待交运";
                break;
            case Application_Model_wayBillItem::Interior_Outstorage:
                return "已交运";
                break;
            case Application_Model_wayBillItem::Interior_PickError:
                return "拣货异常";
                break;
            case Application_Model_wayBillItem::Interior_System:
                return "已入系统";
                break;
            case Application_Model_wayBillItem::Interior_Singleno:
                return "已出转单";
                break;
            case Application_Model_wayBillItem::Interior_Transportation:
                return "已上网";
                break;
            case Application_Model_wayBillItem::Interior_OverSystem:
                return "入系统超期";
                break;
            case Application_Model_wayBillItem::Interior_Oversingleno:
                return "转单超期";
                break;
            case Application_Model_wayBillItem::Interior_OutTransportation:
                return "上网异常";
                break;
            case Application_Model_wayBillItem::Interior_Overachieve:
                return "签收预警";
                break;
            case Application_Model_wayBillItem::Interior_Achieve:
                return "已经完成";
                break;
            case Application_Model_wayBillItem::Interior_Cancel:
                return "已经取消";
                break;
            
        }
    }

    public function getchannelname() {
        if ($this->_channer) {
            return Application_Model_ExpressChannel::load($this->_channer);
        }
    }

    /**
     * 获取发货渠道名称
     */
    public function getagentcompname() {
        if ($this->_agentId) {
            return Application_Model_AgentCompany::load((int) $this->_agentId);
        }
    }

    public static function byaddbill($arrre, $idlist) {
        $arrid = explode(",", $idlist);
        $shipFee = 0;
        foreach ($arrid as $key => $value) {
            if ($value != '') {
                $uwhere['id = '] = $value;
                $result = Application_Model_StoreItem::getDao()->queryOne($uwhere);
                $shipFee = $shipFee + $result->cnShipFee;
                if ($result->state == Application_Model_StoreItem::STATUS_Sended) {
                    return 2;
                }
            }
        }
        $billItem = new Application_Model_wayBillItem();
        foreach ($arrre as $key => $value) {
            $billItem->$key = $value;
        }
        $billItem->dateCreated = date("Y-m-d H:i:s");
        $billItem->shipFee = $shipFee;
        $billItem->status = Application_Model_wayBillItem::STATUS_Processing;
        $billItem->shipFeeconfig = 0;
        $billItem->weight = 0;
        $billItem->lastdate = date("Y-m-d H:i:s");
        $billItem->fee = 0;
        $billItem->lwhth = "**";
        $billItem->channer = 0;
        $billItem->reportFee = 0;
//        var_dump($billItem);exit;
        $billItem->save();
        foreach ($arrid as $key => $value) {
            if ($value != '') {
                $uwhere['id = '] = $value;
                $result = Application_Model_StoreItem::getDao()->queryOne($uwhere);
                $result->wayId = $billItem->id;
                $result->wyid = $billItem->id;
                $result->save();
            }
        }
        Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_addbill, $billItem->billNo, $billItem->userId);
        return 1;
    }

    /**
     * 获取运送方式的信息
     */
    public static function byShipcode($id) {
        return Application_Model_ExpressChannel::load($id);
    }

    /**
     * 快递接口
     * @param type $typeCom 快递类型
     * @param type $typeNu  快递单号
     * @return type
     */
    public static function expressUrl($typeCom, $typeNu) {
        $AppKey = '76f5b960649455ab'; //请将XXXXXX替换成您在http://kuaidi100.com/app/reg.html申请到的KEY
        //优先使用curl模式发送数据
        $url = "http://www.kuaidi100.com/applyurl?key=$AppKey&com=$typeCom&nu=$typeNu";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $get_content = curl_exec($curl);
        curl_close($curl);
        return $get_content;
    }

    /**
     * 发货
     */
    public static function shipments($billid, $uparr, $operate) {

        $result = Application_Model_wayBillItem::load($billid);
        if ($result != '') {
            if ($operate == "single") {
                Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_billsingle, $result->billNo, $result->userId);
                if ($result->refundMoney == null || $result->refundMoney == "" || $result->refundMoney == 0) {
                    if ($uparr['refundMoney'] != 0) {
                        //修改金额
                        $uwhere[' id = '] = $result->userId;
                        $userdetail = Application_Model_UserAccount::getDao()->queryOne($uwhere);
                        $beforeMoney = $userdetail->money;
                        $userdetail->money = $userdetail->money + $uparr['refundMoney'];
                        $afterMoney = $userdetail->money;
                        $userdetail->save();
                        $history = new Application_Model_UserAccountHistory(); //添加记录
                        $history->type = 1;
                        $history->beforeMoney = $beforeMoney;
                        $history->afterMoney = $afterMoney;
                        $history->comment = '国际运单' . $result->billNo . '退还费';
                        $history->relaseId = $billid;
                        $history->dateCreated = date("Y-m-d H:i:s");
                        $history->state = 1;
                        $history->accountId = $result->userId;
                        $history->save();
                        Application_Model_Operate::intooperate($uparr['refundMoney'], Application_Model_Operate::Type_billrefund, $result->billNo, $result->userId);
                    }
                }
            }
            foreach ($uparr as $key => $val) {
                $result->$key = $val;
            }
            $result->save();
            if ($operate == "singment") {
                Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_billshipment, $result->billNo, $result->userId);
                $storewhere[' wayId'] = $billid;
                $storitemdetail = Application_Model_StoreItem::getDao()->queryAll($storewhere);
                foreach ($storitemdetail as $key => $storeval) {
                    $storeval->state = Application_Model_wayBillItem::STATUS_Sended;
                    $storeval->dateOut = date("Y-m-d H:i:s");
                    $storeval->save();
                }
                $expressItem = Application_Model_ExpressChannel::load($uparr["channer"]);
                if ($expressItem) {
                    if ($expressItem->key) {
                        $logItem = new Application_Model_logisticslogItem();
                        if ($result->expressId == 7) {
                            $logItem->opRemark = $expressItem->key . "(悠奇专线)已取件，待出单";
                        } else {
                            if ($expressItem->key == "联邦" || $expressItem->key == "DHL" || $expressItem->key == "UPS" || $expressItem->key == "澳大利亚EMS") {
                                $logItem->opRemark = $expressItem->key . "已取件，待出单";
                            } else {
                                $logItem->opRemark = $expressItem->key . "已取件";
                            }
                        }
                        $logItem->opDate = date("Y-m-d H:i:s");
                        $logItem->opUser = 1;
                        $logItem->opState = 0;
                        $logItem->wayId = $billid;
                        $logItem->save();
                    }
                }
            }
            return true;
        } else {
            return false;
        }
    }

    public static function getDelayAll($interior) {
        $where[" interior = "] = $interior;
        $where[" and status = "] = Application_Model_wayBillItem::STATUS_Sended;
        return self::getDao()->queryAll($where);
    }

    public static function bybillNo($billNo) {
        $where[" billNo = "] = $billNo;
        return Application_Model_wayBillItem::getDao()->queryOne($where);
    }

    public function setBillAgent($arrAgent,$description = null) {
        foreach ($arrAgent as $key => $val) {
            $this->$key = $val;
        }
        $this->save();
        $this->addBillLog($arrAgent["interior"]);
        if($description != null){
            $this->addBillLog(Application_Model_WayLog::Type_BillVolume,$description);
        }
    }

    public function setWeights($Weight, $type) {
        $this->editWeight($type, $Weight);
    }

    public function inFirstFollow() {
        Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_billshipment, $this->_billNo, $this->_userId);
        $storewhere[' wayId'] = $this->_id;
        $storitemdetail = Application_Model_StoreItem::getDao()->queryAll($storewhere);
        foreach ($storitemdetail as $key => $storeval) {
            $storeval->state = Application_Model_wayBillItem::STATUS_Sended;
            $storeval->dateOut = date("Y-m-d H:i:s");
            $storeval->save();
        }
        $logItem = Application_Model_logisticslogItem::getByWayId($this->_id);
        if (!$logItem) {
            $expressItem = Application_Model_ExpressChannel::load($this->_channer);
            if ($expressItem) {
                if ($expressItem->key) {
                    $logItem = new Application_Model_logisticslogItem();
                    if ($this->_expressId == 7) {
                        $logItem->opRemark = $expressItem->key . "(悠奇专线)已取件，待出单";
                    } else {
                        if ($expressItem->key == "联邦" || $expressItem->key == "DHL" || $expressItem->key == "UPS" || $expressItem->key == "澳大利亚EMS") {
                            $logItem->opRemark = $expressItem->key . "已取件，待出单";
                        } else {
                            $logItem->opRemark = $expressItem->key . "已取件";
                        }
                    }
                    $logItem->opDate = date("Y-m-d H:i:s");
                    $logItem->opUser = 1;
                    $logItem->opState = 0;
                    $logItem->wayId = $this->_id;
                    $logItem->save();
                }
            }
        }
    }

    /*
     * 受理
     */

    public static function getUpstatus($id,$payWeight) {
//        $arrid = explode(",", $idlist);
//        for ($i = 0; $i < count($arrid); $i++) {
//            $result = Application_Model_wayBillItem::load($arrid[$i]);
//            if ($result != '') {
//                if ($result->status == Application_Model_wayBillItem::Interior_Processing) {
//                    $result->status = Application_Model_wayBillItem::STATUS_Confrimed;
//                    $result->interior = Application_Model_wayBillItem::Interior_Confrimed;
//                    $result->logistics = "";
//                    $result->save();
//                    $result->addBillLog(Application_Model_wayBillItem::Interior_Confrimed);
//                    Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_billaccept, $result->billNo, $result->userId);
//                }else{
//                    return 0;
//                }
//            }
//        }
//        return 1;
        $result = Application_Model_wayBillItem::load($id);
        if ($result != '') {
            if ($result->status == Application_Model_wayBillItem::Interior_Processing) {
                $result->status = Application_Model_wayBillItem::STATUS_Confrimed;
                $result->interior = Application_Model_wayBillItem::Interior_Confrimed;
                $result->paymentWeight = $payWeight*1000;
                $result->logistics = "";
                $result->save();
                $result->addBillLog(Application_Model_wayBillItem::Interior_Confrimed);
                Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_billaccept, $result->billNo, $result->userId);
            }else{
                return 0;
            }
        }
        return 1;
    }
    
    public function addBillLog($interior,$description = null)
    {
        
        $billLogItem = Application_Model_WayLog::getByWayIdInterior($this->_id, $interior);
        if(!$billLogItem){
            $billLogItem = new Application_Model_WayLog();
            $billLogItem->wayId = $this->_id;
            $billLogItem->operateType = $interior;
        }
        $billLogItem->dateCreated = date("Y-m-d H:i:s");
        $billLogItem->operator = Uuch_Util::decryptString($_COOKIE["__adminusername"]);
        if($description != null){
            $billLogItem->description = $description;
        }else{
            $billLogItem->description = "运单状态更改为：".$this->getinteriorname();
        }
        $billLogItem->save();
    }

    /**
     * 取消运单
     */
    public static function getcancel($id) {
        $result = Application_Model_wayBillItem::load($id);
        if ($result != '') {
            if ($result->status == Application_Model_wayBillItem::STATUS_Processing || $result->status == Application_Model_wayBillItem::STATUS_ExpressBack) {
                $result->status = Application_Model_wayBillItem::STATUS_Cancel;
                $result->dateCreated = date("Y-m-d H:i:s");
                $result->interior = Application_Model_wayBillItem::Interior_Cancel;
                if ($result->discountFee > 0) {
                    $couponItem = Application_Model_Coupon::byrelevance($result->id);
                    if ($couponItem) {
                        $couponItem->status = 1;
                        $couponItem->useTime = "";
                        $couponItem->relevance = "";
                        $couponItem->save();
                    }
                }
                $result->save();
                Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_billcancel, $result->billNo, $result->userId);
                $swhere[' wayId = '] = $id;
                $storerow = Application_Model_StoreItem::getDao()->queryAll($swhere);
                foreach ($storerow as $key => $val) {
                    $val->wyid = $id;
                    $val->wayId = 0;
                    $val->state = 1;
                    $val->save();
                }
                $uwhere[' id = '] = $result->userId;
                $userdetail = Application_Model_UserAccount::getDao()->queryOne($uwhere);
                $beforeMoney = $userdetail->money;
                $userdetail->money = $userdetail->money + $result->shipMoney;
                $afterMoney = $userdetail->money;
                $userdetail->save();
                $history = new Application_Model_UserAccountHistory();
                $history->type = 1;
                $history->beforeMoney = $beforeMoney;
                $history->afterMoney = $afterMoney;
                $history->comment = '运单：' . $result->billNo . '退单费';
                $history->dateCreated = date("Y-m-d H:i:s");
                $history->relaseId = $id;
                $history->state = 10;
                $history->accountId = $result->userId;
                $history->save();
                Application_Model_Operate::intooperate($result->shipMoney, Application_Model_Operate::Type_billcanre, $result->billNo, $result->userId);
                return 2;
            }
            return 22;
        } else {
            return 6;
        }
    }

    public static function getDelaySystemAll() {
        $where[" interior = "] = Application_Model_wayBillItem::Interior_Outstorage;
        return self::getDao()->queryAll($where);
    }
     public function getlocationName()
    {
        $result = Application_Model_StoreLocation::getDao()->queryAll(array("userId"=>  $this->_userId));
        if($result){
            $locationName = "";
            foreach ($result as $value) {
                $locationName.= $value->locationNo.",";
            }
            return $locationName;
        }else{
            return "还没有绑定仓库位，请耐心寻找。";
        }
    }
    
    public function getstorecount()
    {
        $where[" userid = "] = $this->_userId;
        $where[" and state in "] = "(".Application_Model_StoreItem::STATUS_InStored.",".Application_Model_StoreItem::STATUS_CheckIn.",".Application_Model_StoreItem::STATUS_Picking.")";
        $where[" and (isdelete = 0 or isdelete is null) and "] = 1;
        $countStore = Application_Model_StoreItem::getDao()->count($where);
        if($countStore == 0){
            Application_Model_StoreLocation::byUseridRemoveLocation($this->_userId);
        }
    }
    
    public function byWeightCityExpressCost()
    {
        if ($this->ExpressBy->isVolume == 1) {
            if ($this->_volumeWeight > ($this->_productWeight + $this->_bagWeight)) {
                $rweight = $this->_volumeWeight / 1000;
            } else {
                $rweight = (($this->_productWeight + $this->_bagWeight) / 1000);
            }
        } else {
            $rweight = $this->_volumeWeight / 1000;
        }
        $weight = (int)$rweight + 1;
        $channelId = "(";
        if($this->ExpresschannelOne){
            foreach ($this->ExpresschannelOne as $value) {
                if($value){
                    $channelId.= $value->id.",";
                }
            }
        }
        $channelId.= "0)";
        $where[" channelId in "] = $channelId;
        $where[" and cityId = "] = $this->_state;
        $where[" and weight = "] = $weight;
//        var_dump($where);exit;
        return Application_Model_ExpressCost::getDao()->queryAll($where," price asc");
    }
    public static function getChannelIdWeightByExpress($expressId,$weight,$city)
    {
        $channelItem = Application_Model_Expressbychannel::getExpressIdByChannel($expressId);
        $channelId = "(";
        foreach ($channelItem as $value) {
            $channelId.= $value->expressChannelId.",";
        }
        $channelId.= "0)";
        $where[" channelId in "] = $channelId;
        $where[" and cityId = "] = $city;
        $where[" and weight = "] = (int)($weight/1000) + 1;
       
        return Application_Model_ExpressCost::getDao()->queryAll($where," price asc");
    }
    public function AddSingle()
    {
        $where[" outstoreno = "] = $this->_agentNo;
        $singItem = Application_Model_Single::getDao()->queryOne($where);
        if(!$singItem){
            $singItem = new Application_Model_Single();
        }
        $singItem->outstoreno = $this->_agentNo;
        $singItem->agentid = $this->_agentId;
        if($this->_logistics){
            $singItem->ischange = 1;
        }
        $singItem->save();
        return true;
    }
    
    public function getbillurl()
    {
        if($this->_interior == Application_Model_wayBillItem::Interior_Incoice)
        {
            return "/admini/managewaybill/picking/id/".$this->_id;
        }else{
            return "/admini/managewaybill/billaccep/id/".$this->_id;
        }
    }
    
    public function getBillNoInvoice()
    {
        return Application_Model_invoice::bybillNo($this->_billNo);
    }
    
    public static function getBillIdAffirm($idlist)
    {
        $arrid = explode(",", $idlist);
        for ($i = 0; $i < count($arrid); $i++) {
            $result = Application_Model_wayBillItem::load($arrid[$i]);
            if ($result != '') {
                if ($result->interior == Application_Model_wayBillItem::Interior_AffirmChannel || $result->status == Application_Model_wayBillItem::STATUS_Confrimed) {
                    $result->status = Application_Model_wayBillItem::STATUS_Confrimed;
                    $result->interior = Application_Model_wayBillItem::Interior_Outstorage;
                    $result->logistics = "";
                    $result->save();
                    $result->addBillLog(Application_Model_wayBillItem::Interior_Outstorage);
                    Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_AffirmChannel, $result->billNo, $result->userId);
                }else{
                    return 0;
                }
            }
        }
        return 1;
    }
    /**
     * 修改运单状态
     * @param type $id
     * @param type $status
     * @param type $istype
     */
    public static function editbills($id,$status,$istype)
    {
        $where[' type = '] = $istype;
        $where[' and glid = '] = $id;
        $reslut = Application_Model_problem::getDao()->queryOne($where);
        if($reslut){
            $reslut->delete();
        }
        $bill = Application_Model_wayBillItem::load($id);
        if($status == self::Interior_Achieve || $status == self::Interior_Cancel || $status == self::Interior_Processing){
            $bill->status = $status;
        } else if ($status < self::Interior_Outstorage){
            $bill->status = self::STATUS_Confrimed;
        } else {
            $bill->status = self::STATUS_Sended;
        }
        $bill->interior = $status;
        $bill->save();
        $bill->getBillIdDelLog();
        Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_billstatus, $bill->billNo, $bill->userId, $bill->getinteriorname());
        return 1;
    }
    
    public static function affirmfind($billid,$storeid)
    {
        $billItem = self::load($billid);
        if($billItem->interior == Application_Model_wayBillItem::Interior_PickError){
            $billstoreItem = Application_Model_WayItem::getWayIdStoreIdByStatus($billid, $storeid);
            if($billstoreItem->status == Application_Model_WayItem::Status_Lose){
                $billstoreItem->status = Application_Model_WayItem::Status_Picking;
                $billstoreItem->save();
                foreach ($billItem->getItems() as $itemVal) {
                    if($itemVal->status == Application_Model_WayItem::Status_Initial || $itemVal->status == Application_Model_WayItem::Status_Lose){
                        return 1;
                    }
                }
                $billItem->interior = self::Interior_Picking;
                $billItem->save();
                $billItem->addBillLog(self::Interior_Picking);
                return 1;
            }else{
                return 3;
            }
        }else{
            return 2;
        }
    }
    
}
